package com.jjyu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjyu.dao.OrderMapper;
import com.jjyu.entity.Inventory;
import com.jjyu.entity.Order;
import com.jjyu.entity.OrderItem;
import com.jjyu.entity.User;
import com.jjyu.service.InventoryService;
import com.jjyu.service.OrderItemService;
import com.jjyu.service.OrderService;
import com.jjyu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private OrderItemService orderItemService;

    @Transactional(propagation = Propagation.REQUIRED,
            rollbackFor = Exception.class,
            noRollbackFor = ArithmeticException.class,
            timeout = 4)
    public boolean createOrder(Integer userId, HashMap<Integer, Integer> orderItems) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return false;
        }
        // 验证餐品库存是否充足并计算订单项金额
        Double totalPrice = 0.0;
        HashMap<Inventory, Double> orderItemPrices = new HashMap<>();
        for (Integer itemId : orderItems.keySet()) {
            Inventory inventory = inventoryService.getById(itemId);
            if (inventory.getQuantity() < orderItems.get(itemId)) {
                return false;
            }

            // 减少库存
            inventory.setQuantity(inventory.getQuantity() - orderItems.get(itemId));
            inventoryService.updateById(inventory);

            orderItemPrices.put(inventory, orderItems.get(itemId) * inventory.getPrice());
            totalPrice += orderItemPrices.get(inventory);

        }
        // 创建订单记录
        Order order = new Order();
        //随机生成一个订单ID
        Integer orderId = new Random().nextInt(100000);
        order.setOrderId(orderId);
        order.setUserId(userId);
//        try{
//            Thread.sleep(3100);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        //int i = 1 / 0;
        order.setTotalAmount(BigDecimal.valueOf(totalPrice));
        orderMapper.insert(order);
        // 创建订单项记录
        for (Inventory inventory : orderItemPrices.keySet()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setItemName(inventory.getItemName());
            orderItem.setRestaurantId(inventory.getRestaurantId());
            orderItem.setQuantity(orderItems.get(inventory.getInventoryId()));
            orderItem.setPrice(BigDecimal.valueOf(orderItemPrices.get(inventory)));
            orderItemService.save(orderItem);
        }
        return true;
    }
}
